﻿using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using MySql.Data.MySqlClient;
using SCM.Extensions.Ledger;
using System.Text;
using System.Threading;

namespace SCM.API.Read.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SignalRController : ControllerBase
    {
        private readonly IHubContext<SignalRHub> _hubContext;

        public SignalRController(IHubContext<SignalRHub> hubContext)
        {
            _hubContext = hubContext;
        }
        [HttpGet]
        public async Task<IActionResult> Push()
        {
            try
            {
                var sqlBuilder = new StringBuilder();

                sqlBuilder.Append(@"SELECT 
                                        a.id,
                                        a.Code,
                                        a.DateTime,
                                        a.BusinessType,
                                        c.STId,
                                        c.STName,
                                        d.DepotId,
                                        d.DepotName,
                                        a.StockId,
                                        a.IncomingQuantity,
                                        a.IncomingMoney,
                                        a.State,
                                        a.isDel
                                FROM EnterOutModel a  join  DepotModel      d on a.DepotId=d.DepotId
                                                    join Stocking         f on a.StockId=f.Id
                                                    join Stocking_Type c on a.STId=c.STId
                                    WHERE a.IsDel=0  and d.IsDel=0  and f.IsDeleted=0 and c.IsDeleted=0  ");

                using var conn = new MySqlConnection("server=120.27.210.76;uid=wms_user;pwd=MyPassword123!;database=warehousemanagement;CharSet=utf8mb4;");
                await conn.OpenAsync();

                var data = await conn.QueryAsync<EnterOutDTO>(sqlBuilder.ToString());
                await _hubContext.Clients.All.SendAsync("ReciveenterOutDTOs", data.ToList());
                return Ok($"推送成功，共{data.Count()}条数据");
            }
            catch (Exception ex)
            {

                return BadRequest($"推送失败{ex.Message}");
            }
        }
    }
}
